var pool = require('../../config/mysql.connection');
var mapping = require('./mapping/warranty.mapping');
var userMap = require('./mapping/user.mapping');
var redis = require('../../config/redis');

var redisData = userMap.redisData;
var WarrantyRedisData = [];
var redisSaveCount = 0;

module.exports = {
    removeWarranty:function(param , callback){
        pool.getConnection(function(err , connection){
            connection.query(mapping.deleteWarranty,[param.id],function(err,result){
                if(err){
                    throw err;
                }
                callback(result);
                connection.release();
            });
        });
    },
    uploadWarranty:function(param , callback){
        pool.getConnection(function(err , connection){
            connection.query(mapping.uploadWarranty(param),function(err,result){
                if(err){
                    throw err;
                }

                if(result){
                    callback(result);
                }
                connection.release();
            });
        });
    },
    addWarranty:function(param , callback){
        pool.getConnection(function(err , connection){
            connection.query(mapping.insertWarranty(param),function(err,result){
                if(err){
                    throw err;
                }

                if(result){
                    callback(result);
                }
                connection.release();
            });
        });
    },
	getWarrantyAll:function(param , callback){
		pool.getConnection(function(err,connection){
			connection.query(mapping.getWarrantyAll(param),function(err,result){
				if(err){
					throw err;
				}
				callback(result);
				connection.release();
			});
		});
	},
	getRedisArr:function(){
        var redisName = {'interest':true,'credit':true,'loanCharge':true,'datum':true,'debtAsk':true,
        'lendingAsk':true,'safeWork':true};
        WarrantyRedisData = [];
        for(var i in redisData){
            if(redisName[redisData[i].name]){
                WarrantyRedisData.push(redisData[i]);
            }
        }
        return this;
    },
	getRedisData:function(resObject,callback){
        var _this = this;
        var data = WarrantyRedisData[redisSaveCount];
        redis.get(data.name,function(err,res){
        	if(err){
        		throw err;
        	}
        	resObject[data.name] = JSON.parse(res);
        	if(redisSaveCount < WarrantyRedisData.length-1){
        		redisSaveCount++;
        		_this.getRedisData(resObject,callback);
        	}else{
        		redisSaveCount = 0;
        		//redis.end();
        		callback(resObject);
        	}
        });
    }
};